package com.itheima;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class ServerReaderThread extends Thread{
    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
         try{
             //1.从socket获取当前客户端的输入流
             BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
             String msg;
             while((msg=br.readLine())!=null){
                 //2.服务器接收到了客户端消息以后，是需要将其推送给所有的socket
                 Scanner scanner=new Scanner(System.in);
                 System.out.println("选择群发还是私发"+Server.allSocketOnLine.get(this.socket)+"正在发言，刚转化到发言时双击回车");
                 String flag= scanner.nextLine();
                 if(flag.equals("群发")){
                     sendMsgToAllClient(msg);
                 }else if(flag.equals("私发")){
                     Scanner scanner1=new Scanner(System.in);
                     System.out.println("输入收信人");
                     String man=scanner1.nextLine();
                     sendMsgOne(msg,man);
                 }

             }
         }catch (Exception e){
             System.out.println("当前有人下线了");
             //删除从当前socket集合中
             Server.allSocketOnLine.remove(socket);
         }
    }

    private void sendMsgOne(String msg,String man) throws IOException {
        Set<Map.Entry<Socket, String>> entries = Server.allSocketOnLine.entrySet();
        for (Map.Entry<Socket,String> entry : entries) {
            if(entry.getValue().equals(man)){
                PrintStream ps=new PrintStream(entry.getKey().getOutputStream());
                ps.println(msg);
                ps.flush();
            }
        }
    }

    //将当前客户端发来的消息发送给所有的socket
    private void sendMsgToAllClient(String msg) throws IOException {
        Set<Map.Entry<Socket, String>> entries = Server.allSocketOnLine.entrySet();
        for (Map.Entry<Socket,String> entry : entries) {
            if(entry.getKey()!=this.socket){
                PrintStream ps = new PrintStream(entry.getKey().getOutputStream());
                ps.println(msg);
                ps.flush();
            }
        }
    }
}
